package com.example.linearlayoutdemo.network.auth.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.linearlayoutdemo.MyApplication;
import com.example.linearlayoutdemo.network.auth.model.User;
import com.google.gson.Gson;

/**
 * SharedPreferences工具类，用于保存用户登录状态和Token
 */
public class SharedPreferencesUtil {
    private static final String PREF_NAME = "auth_prefs";
    private static final String KEY_USER = "user_token";
    private static final String KEY_AUTO_LOGIN = "auto_login";

    private static SharedPreferencesUtil instance;
    private final SharedPreferences sharedPreferences;
    private final Gson gson;

    private SharedPreferencesUtil(Context context) {
        sharedPreferences = MyApplication.getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }

    public static synchronized SharedPreferencesUtil getInstance(Context context) {
        if (instance == null) {
            instance = new SharedPreferencesUtil(context);
        }
        return instance;
    }

    /**
     * 保存用户信息
     */
    public void saveUser(User user) {
        String usertoken = user.getToken();
        sharedPreferences.edit().putString(KEY_USER, usertoken).apply();
    }

    /**
     * 获取保存的用户信息
     */
    public User getUser() {
        String userToken = sharedPreferences.getString(KEY_USER, null);
        if (userToken != null) {
            User user = new User();
            user.setToken(userToken);
            return user;
        }
        return null;
    }

    /**
     * 保存自动登录状态
     */
    public void setAutoLogin(boolean autoLogin) {
        sharedPreferences.edit().putBoolean(KEY_AUTO_LOGIN, autoLogin).apply();
    }

    /**
     * 获取自动登录状态
     */
    public boolean isAutoLogin() {
        return sharedPreferences.getBoolean(KEY_AUTO_LOGIN, false);
    }

    /**
     * 清除登录信息
     */
    public void clearLoginInfo() {
        sharedPreferences.edit().remove(KEY_USER).remove(KEY_AUTO_LOGIN).apply();
    }

    /**
     * 检查是否有保存的登录信息
     */
    public boolean hasLoginInfo() {
        return sharedPreferences.contains(KEY_USER) && getUser() != null && getUser().getToken() != null;
    }
}

